(function() {

    function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    var appsecret = 'd1109525e22df1b046b012348f412e81',
        typepay = '', //微信还是支付宝扫码
        decitem = '',
        errcode = '',
        phone = '',
        id = '',
        price = '',
        course = '',
        openid = '',
        sy_money = '', //剩余钱数
        paytypesuc = 1, //1微信  2支付宝  3小七币  默认为1
        uid = '', //用户id
        priceyao = '',
        sy_money = '',
        card_money = '',
        xqb_money = '',

        // 一拍测试
        // request = 'https://n.qikeya.com/erp_api/public/index.php/',
        // request1 = 'https://n.qikeya.com/saas/public/index.php/',

        request = 'https://api-erp.qikeya.cn/',
        request1 = 'https://appapi.qikeya.cn/',


        url = 'qkyPay/jnpay/ordernewjn.html'

        url1 = window.location.href.split(':')[0];

    var is_skillfrom = 0; //1技能卡充值 0线上支付 
    var ismy = 0; //0扫码支付 1自行支付 2押金
    var ucp_id = GetQueryString("ucp_id");
    var appid = '171pk17641pkzone1';
    if (GetQueryString("is_skillfrom")) {
        is_skillfrom = GetQueryString("is_skillfrom");
    }

    if (GetQueryString("ismy")) {
        ismy = GetQueryString("ismy");
    }
    if (Number(ismy) >= 1) {
        $('.successbottom .successactive').html('返回');
        if (Number(ismy) == 2) {
            $('#priceid .itemleft').html('(押金)');
        }
    }

    if (Number(is_skillfrom) == 1) {
        phone = GetQueryString("phone");
        price = GetQueryString("price");
        window.sessionStorage.setItem('phone', phone);
        window.sessionStorage.setItem('price', price);
    }
    // console.log(order_sn);
    if (GetQueryString("typeerrcode")) { //支付宝支付回调
        var typeerrcode = GetQueryString("typeerrcode");
        if (Number(typeerrcode) == 1) { //支付成功
            // $('.detailsuccess').fadeIn();
            paysuc(2);
        } else {
            alert('支付失败');
            $('.orderbut').removeClass('orderbutactive');
        }
    }



    window.sessionStorage.setItem('ucp_id', ucp_id);
    window.sessionStorage.setItem('appid', appid);
    window.sessionStorage.setItem('is_skillfrom', is_skillfrom);
    window.sessionStorage.setItem('ismy', ismy);

    // https://oss.qikeya.cn/webpage/aboutus.html




    // // 获取信息
    // CRMwx();

    paymenttype();
    // 获取支付方式
    function paymenttype() {
        if (Number(is_skillfrom) == 1) {
            $('#xiaopay').hide();
            $('#rechargeable').hide();
            // $('#zfupay').addClass('everypay2').removeClass('everypay3');
        }
        IsWeixinOrAlipay(1);
    }

    function IsWeixinOrAlipay(is_ali) {

          
        var ua = window.navigator.userAgent.toLowerCase();   //判断是不是微信
          
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {  
            typepay = "WeiXIN";
            $('#xiaopay').find('.everyright img').attr('src', 'img/choose.png');
            $('#wechatpay').find('.everyright img').attr('src', 'img/chooseactive.png');
            $('#zfupay').hide();
            // $('#wechatpay').addClass('everypay2');
            paytypesuc = 1;

            if (window.sessionStorage.openid) {
                layer.open({
                    content: '登录成功',
                    skin: 'msg',
                    time: 1 //1秒后自动关闭
                });
                $('.orderbut').removeClass('orderbutactive');
                $('.detaillogin').fadeOut();
            } else {
                // 先静默授权
                $('.detaillogin').fadeIn();
                // window.location.href = request1 + 'api/user/getOpenid?appid=' + appid + '&route=' + url + '&to=' + url1 + '&is_act=7';
            }  
        } 
        else if (ua.match(/Alipay/i) == "alipay") { //支付宝
            typepay = "Alipay"; 
            $('#xiaopay').find('.everyright img').attr('src', 'img/choose.png');
            $('#zfupay').find('.everyright img').attr('src', 'img/chooseactive.png');
            $('#wechatpay').hide();
            paytypesuc = 2;
        } else {
            typepay = 'all'
            $('#xiaopay').find('.everyright img').attr('src', 'img/choose.png');
            $('#wechatpay').find('.everyright img').attr('src', 'img/chooseactive.png');
            $('#zfupay').find('.everyright img').attr('src', 'img/choose.png');
            paytypesuc = 1;
        }
    }
    if (Number(is_skillfrom) <= 0) {
        if (Number(ismy) == 2) {
            $('#courseqic').show();
            CRMyjpay();
        } else {
            if (sessionStorage.getItem('payis')) {
                setTimeout(function() {
                    CRMwx();
                }, 1000)
            } else {
                CRMwx();
            }
        }
    } else {
        if (sessionStorage.getItem('payisji')) {
            setTimeout(function() {
                cardPayStatus();
            }, 1000)
        } else {
            cardPayStatus();
        }
    }
    $('.gologin').click(function() {
        $('.detaillogin').fadeOut();
        // console.log(request1 + 'api/user/getOpenid?appid=' + appid + '&route=' + url + '&to=' + url1 + '&is_act=11');
        window.location.href = request1 + 'api/user/getOpenid?appid=' + appid + '&route=' + url + '&to=' + url1 + '&is_act=11';
    })

    function CRMyjpay() {
        $('#courseid').hide();
        $.ajax({
            url: request + 'crmapi/Pay/stuClassInfoJn',
            data: {
                id: ucp_id,
            },
            headers: {
                appid: appid
            },
            dataType: "json",
            success: function(res) {
                if (Number(res.errcode) == 0) {
                    $('.all').show();
                    $('.noall').hide();
                    var data = res.data;
                    decitem = data;
                    window.localStorage.setItem('decdatastu', JSON.stringify(data));
                    price = data.yj_money;
                    xqb_money = data.money;
                    course = data.class_name + '(押金)';
                    // console.log(course)
                    $('#rechargeable').hide();

                    $('#xiaopay').hide();
                    $('#coursename_qi').html(data.class_name);
                    $('#name').html(data.user_name);
                    $('#phone').html(data.tel);
                    $('.everytitle span').html('(' + data.money + ')');
                    $('#price').html(data.yj_money);
                    // $('#price input').attr("value", data.yj_money);
                    if (Number(ismy) == 2) {
                        $('#price input').attr("disabled", 'disabled');
                    }
                } else {
                    $('.noall').show();
                    $('.all').hide();
                    $('.noall p').html(res.msg);
                }
                $('.showerViplo').hide();
            }
        })
    }


    function cardPayStatus() {
        $.ajax({
            url: request + 'crmapi/Pay/cardPayStatus',
            data: {
                log_id: ucp_id,
            },
            headers: {
                appid: appid
            },
            dataType: "json",
            success: function(res) {
                if (Number(res.errcode) == 0) {
                    $('.all').show();
                    $('.noall').hide();
                    $('#phone').html(phone);
                    $('#isshowname').hide();
                    $('#price').html(price);

                    $('#courseid .itemleft').html('充值类型');
                    $('#priceid .itemleft').html('(充值金额)');
                    course = '技能提升卡充值'
                    $('#coursename').html(course);
                } else {
                    $('.noall').show();
                    $('.all').hide();
                    $('.noall p').html(res.msg);
                }
                $('.showerViplo').hide();
            }
        })
    }

    function CRMwx() {
        $.ajax({
            url: request + 'crmapi/Pay/crmWxDataLast',
            data: {
                ucp_id: ucp_id,
            },
            headers: {
                appid: appid
            },
            dataType: "json",
            success: function(res) {
                if (Number(res.errcode) == 0) {
                    $('.all').show();
                    $('.noall').hide();
                    var data = res.data;
                    decitem = data;
                    window.localStorage.setItem('decdatastu', JSON.stringify(data));
                    price = data.price;
                    course = data.course;
                    sy_money = data.sy_money;
                    xqb_money = data.user_money;
                    card_money = data.card_money;
                    uid = data.user_id;
                    $('#coursename').html(data.course);
                    $('#name').html(data.name);
                    $('#phone').html(data.phone);
                    phone = data.phone;
                    $('.everytitle span').html('(' + data.user_money + ')');
                    if ((Number(price) != 0) && (price != '')) {
                        // $('#price').attr("value", price);
                        $('#price').html(price);
                    }
                    // console.log(ismy)
                    // if (Number(ismy) >= 1) {
                    //     $('#price input').attr("disabled", 'disabled');
                    // }
                    if (Number(data.card_money) > 0) {
                        $('#rechargeable .everytitle span').html('(' + data.card_money + ')');
                        $('#rechargeable').show();
                    } else {
                        // $('#zfupay').addClass('everypay2').removeClass('everypay3');
                        $('#rechargeable').hide();
                    }
                } else {
                    $('.noall').show();
                    $('.all').hide();
                    $('.noall p').html(res.msg);
                }
                $('.showerViplo').hide();
            }
        })
    }


    // 点击小七币支付
    $('#xiaopay').click(function() {
        paytypesuc = 3;
        var a = $('#price').html();
        var priceyao1 = a.replace(/\s+/g, "");
        priceyao = Math.floor((priceyao1) * 100) / 100;
        if (Number(priceyao) > Number(xqb_money)) {
            $('.choosepaybottom').html('用户小七币不足');
        } else {
            $('.choosepaybottom').html('立即支付￥' + priceyao)
        }
        $(this).find('.everyright img').attr('src', 'img/chooseactive.png');
        $('#wechatpay').find('.everyright img').attr('src', 'img/choose.png');
        $('#zfupay').find('.everyright img').attr('src', 'img/choose.png');
        $('#rechargeable').find('.everyright img').attr('src', 'img/choose.png');
    })

    // 点击切换到微信支付
    $('#wechatpay').click(function() {
        paytypesuc = 1;
        var a = $('#price').html();
        var priceyao1 = a.replace(/\s+/g, "");
        priceyao = Math.floor((priceyao1) * 100) / 100;
        $('.choosepaybottom').html('立即支付￥' + priceyao)
        $(this).find('.everyright img').attr('src', 'img/chooseactive.png');
        $('#xiaopay').find('.everyright img').attr('src', 'img/choose.png');
        $('#zfupay').find('.everyright img').attr('src', 'img/choose.png');
        $('#rechargeable').find('.everyright img').attr('src', 'img/choose.png');
    })

    // 点击切换到支付宝支付
    $('#zfupay').click(function() {
            paytypesuc = 2;
            var a = $('#price').html();
            var priceyao1 = a.replace(/\s+/g, "");
            priceyao = Math.floor((priceyao1) * 100) / 100;
            $('.choosepaybottom').html('立即支付￥' + priceyao)
            $(this).find('.everyright img').attr('src', 'img/chooseactive.png');
            $('#xiaopay').find('.everyright img').attr('src', 'img/choose.png');
            $('#wechatpay').find('.everyright img').attr('src', 'img/choose.png');
            $('#rechargeable').find('.everyright img').attr('src', 'img/choose.png');
        })
        // 点击切换到技能提升卡支付
    $('#rechargeable').click(function() {
        paytypesuc = 4;
        var a = $('#price').html();
        var priceyao1 = a.replace(/\s+/g, "");
        priceyao = Math.floor((priceyao1) * 100) / 100;
        if (Number(priceyao) > Number(card_money)) {
            $('.choosepaybottom').html('用户技能提升卡余额不足');
        } else {
            $('.choosepaybottom').html('立即支付￥' + priceyao)
        }
        // card_money
        // 
        $(this).find('.everyright img').attr('src', 'img/chooseactive.png');
        $('#xiaopay').find('.everyright img').attr('src', 'img/choose.png');
        $('#wechatpay').find('.everyright img').attr('src', 'img/choose.png');
        $('#zfupay').find('.everyright img').attr('src', 'img/choose.png');
    })


    $('.orderbut').click(function() {

        if ($('.orderbut').hasClass('orderbutactive')) {

        } else {
            //   else if(sy_moneyyao<priceyao){
            //     layer.open({
            //         content: '本次缴费不能大于上次余款',
            //         skin: 'msg',
            //         time: 1 //1秒后自动关闭
            //     });
            // }
            var a = $('#price').html();
            var priceyao1 = a.replace(/\s+/g, "");
            priceyao = Math.floor((priceyao1) * 100) / 100;
            var sy_moneyyao = Math.floor((sy_money) * 100) / 100;
            var reg = /(^[-+]?[1-9]\d*(\.\d{1,2})?$)|(^[-+]?[0]{1}(\.\d{1,2})?$)/;
            if (priceyao == '' || Number(priceyao) <= 0) {
                layer.open({
                    content: '请输入本次缴费金额',
                    skin: 'msg',
                    time: 1 //1秒后自动关闭
                });
            } else if (!reg.test(priceyao1)) {
                layer.open({
                    content: '请输入正确的缴费金额',
                    skin: 'msg',
                    time: 1 //1秒后自动关闭
                });
            } else if (Number(is_skillfrom) == 1 && Number(String(priceyao1).indexOf(".") + 1) > 0) {
                layer.open({
                    content: '充值金额只能为整数',
                    skin: 'msg',
                    time: 1 //1秒后自动关闭
                });
            } else {
                // console.log(899)
                choosepaybottom();
                // $('.showerVip').fadeIn();
                if (Number(paytypesuc) == 3) {
                    if (Number(priceyao) > Number(xqb_money)) {
                        $('.choosepaybottom').html('用户小七币不足');
                    } else {
                        $('.choosepaybottom').html('立即支付￥' + priceyao)
                    }
                } else if (Number(paytypesuc) == 4) {
                    if (Number(priceyao) > Number(card_money)) {
                        $('.choosepaybottom').html('用户技能提升卡余额不足');
                    } else {
                        $('.choosepaybottom').html('立即支付￥' + priceyao)
                    }

                } else {
                    $('.choosepaybottom').html('立即支付￥' + priceyao)
                }
            }
        }
    })

    function choosepaybottom() {
        // $('.choosepaybottom').click(function() {
        if (Number(paytypesuc) == 1) { //微信支付
            var ua = navigator.userAgent.toLowerCase();
            var isWeixin = ua.indexOf('micromessenger') != -1;
            // console.log(isWeixin);
            // return;
            if (isWeixin) {
                $('.showerVip').fadeOut();
                if (window.sessionStorage.openid) {
                    // var openid='oXbpd57B45sOdzn1UpgXoyZ2wx8Q'
                    openid = sessionStorage.getItem('openid');
                    weipay(ucp_id, priceyao, course, openid);
                } else {
                    // 先静默授权
                    $('.detaillogin').fadeIn();
                    // window.location.href = request1 + 'api/user/getOpenid?appid=' + appid + '&route=' + url + '&to=' + url1 + '&is_act=7';
                }
            } else {
                layer.open({
                    content: '请在微信内支付',
                    skin: 'msg',
                    time: 1 //1秒后自动关闭
                });
            }
        } else if (Number(paytypesuc) == 2) {
            $('.showerVip').fadeOut();
            // 支付宝支付 Alipay is_skillfrom
            // console.log(request + 'crmapi/pay/Alipay?id=' + ucp_id + '&appid=' + appid + '&subject=' + course + '&amount=' + priceyao + '&route=' + url + '&from=' + is_skillfrom + '')
            // if (Number(ismy) == 2) {
            //     var is_skillfrom1 = 2;
            // } else {
            //     var is_skillfrom1 = is_skillfrom;
            // }
            var is_skillfrom1 = 3
             console.log(request + 'crmapi/pay/Alipay?id=' + ucp_id + '&appid=' + appid + '&subject=' + course + '&amount=' + priceyao + '&route=' + url + '&from=' + is_skillfrom1 + '')
            window.location.href = request + 'crmapi/pay/Alipay?id=' + ucp_id + '&appid=' + appid + '&subject=' + course + '&amount=' + priceyao + '&route=' + url + '&from=' + is_skillfrom1 + '';
        } else if (Number(paytypesuc) == 4) { //
            // console.log(priceyao);
            xiaopay1(ucp_id, priceyao, course);
        } else { //
            // console.log(priceyao);
            xiaopay(ucp_id, priceyao, course);
        }
    }

    function xiaopay1(ucp_id, price, course) {
        if (Number(price) > Number(card_money)) {
            // console.log(8989);
            layer.open({
                content: '技能提升卡余额不足',
                skin: 'msg',
                time: 1 //1秒后自动关闭
            });
            $('.orderbut').removeClass('orderbutactive');
        } else {
            $('.showerVip').fadeOut();
            payxq(ucp_id, price, 1, phone);
            // if (sessionStorage.getItem('codeyes')) {

            // } else {
            //     window.location.href = 'phonecer.html?ucp_id=' + ucp_id + '&phone=' + phone + '&appid=' + appid + '&amount=' + price + '&from=1';
            // }
        }
    }

    function xiaopay(ucp_id, price, course) {
        // console.log(price)
        // console.log(xqb_money)
        if (Number(price) > Number(xqb_money)) {
            // console.log(8989);
            layer.open({
                content: '用户小七币不足',
                skin: 'msg',
                time: 1 //1秒后自动关闭
            });
            $('.orderbut').removeClass('orderbutactive');
        } else {
            $('.showerVip').fadeOut();
            if (Number(ismy) == 2) {
                var url = 'crmapi/Pay/classSurpluPay';
                var obj = {
                    id: ucp_id
                }
                $.ajax({
                    type: "POST",
                    url: request + url,
                    data: obj,
                    headers: {
                        appid: appid,
                    },
                    dataType: "json",
                    success: function(res) {
                        if (Number(res.errcode) == 0) {
                            paysuc(1);
                            // $('.detailsuccess').fadeIn();
                        } else {
                            layer.open({
                                content: res.data.msg,
                                skin: 'msg',
                                time: 1 //1秒后自动关闭
                            });
                        }
                    }
                })
            } else {
                payxq(ucp_id, price, 0, phone);
                // if (sessionStorage.getItem('codeyes')) {} else {
                //     window.location.href = 'phonecer.html?ucp_id=' + ucp_id + '&phone=' + phone + '&appid=' + appid + '&amount=' + price + '&from=0';
                // }
            }

        }
    }

    function paysuc(type) {
        // if (Number(type) == 2) {
        var decitem1 = JSON.parse(localStorage.getItem('decdatastu'));
        // } else {
        //     var a = $('#price').html();
        //     var priceyao1 = a.replace(/\s+/g, "");
        //     priceyao = Math.floor((priceyao1) * 100) / 100;
        //     var decitem1 = decitem;
        // }
        var obj = {
            price: decitem1.yj_money,
            course: Base64.encode(decitem1.class_name),
            tel: decitem1.tel,
            name: Base64.encode(decitem1.user_name),
        }
        window.location.href = '../sucesspay.html?obj=' + JSON.stringify(obj) + ''
    }

    function payxq(ucp_id, price, from, phone) {
        var obj = {
                ucp_id: ucp_id,
                amount: price,
                // code: message,
                phone: phone,
                from: from
            }
            // console.log(obj)
        $.ajax({
            type: "GET",
            url: request + 'crmapi/pay/surpluPay',
            data: obj,
            headers: {
                appid: appid,
                'token': '',
                'version': 'v1', //版本号
                'fromsource': 5, //来源 
                'device': 'wechat', //设备
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: "json",
            success: function(res) {
                if (Number(res.errcode) == 0) {
                    var data = res.data;
                    sessionStorage.setItem('payis', 1);
                    // $('.detailsuccess').fadeIn();
                    paysuc(1);
                } else {
                    $('.submitbut').removeClass('submitbutactive')
                    layer.open({
                        content: res.msg,
                        skin: 'msg',
                        time: 1 //1秒后自动关闭
                    });
                }
                $('.showerViplo').hide();
            }
        })
    }

    function weipay(ucp_id, price, course, openid) {
        var ua = navigator.userAgent.toLowerCase();
        var isWeixin = ua.indexOf('micromessenger') != -1;
        // console.log(isWeixin);
        // return;
        if (isWeixin) {
            if (Number(ismy) == 2) {
                var is_skillfrom1 = 2;
            } else {
                var is_skillfrom1 = is_skillfrom;
            }
            var obj = {
                id: ucp_id,
                amount: price,
                subject: course,
                openid: openid,
                from:3
                // from: is_skillfrom1
            }
            var url = 'crmapi/pay/wxpay'
            $.ajax({
                type: "POST",
                url: request + url,
                data: obj,
                headers: {
                    appid: appid,
                },
                dataType: "json",
                success: function(res) {
                    if (Number(res.errcode) == 0) {
                        var data = res.data;
                        var data1 = {
                            'appId': data.appId,
                            'nonceStr': data.nonceStr,
                            'package': data.package,
                            'paySign': data.paySign,
                            'signType': data.signType,
                            'timeStamp': data.timeStamp,
                        }
                        sessionStorage.setItem('payisji', 1)
                        callpay(data1);
                    } else {
                        $('.orderbut').removeClass('orderbutactive');
                        layer.open({
                            content: res.msg,
                            skin: 'msg',
                            time: 1 //1秒后自动关闭
                        });
                    }
                }
            })
        }else {
            layer.open({
                content: '请在微信内支付',
                skin: 'msg',
                time: 1 //1秒后自动关闭
            });
        }
    }



    function callpay(data) {
        if (typeof WeixinJSBridge == "undefined") {

            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', this.jsApiCall, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', this.jsApiCall);
                document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall);
            }
        } else {
            jsApiCall(data);
        }
    }

    function jsApiCall(data) {
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest',
            data,
            function(res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    // alert('支付成功');
                    // $('.detailsuccess').fadeIn();
                    paysuc(1);
                } else {
                    alert('支付失败');
                    $('.orderbut').removeClass('orderbutactive');
                }
            }
        );
    }

    // 点击取消支付弹窗
    $('.shownone,.paychoosefalse').click(function() {
        $('.showerVip').fadeOut();
    })


    $('.successbottom').click(function() {
        // payhref
        if (Number(ismy) >= 1) {
            if (localStorage.getItem('payhref')) {
                window.location.href = localStorage.getItem('payhref');
                localStorage.removeItem('payhref');
            } else {
                window.location.href = 'https://www.qikeya.cn/pages/tiku/mytiku/appdowntk';
            }
        } else {
            window.location.href = 'https://www.qikeya.cn/pages/tiku/mytiku/appdowntk';
        }
    })


})();